package com.starblink.post.topicdetail.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.ext.commContext
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.util.ImageUtils
import com.starblink.rocketreserver.SearchHashtagPostQuery
import com.starblink.rocketreserver.fragment.HashtagPostVOF
import com.starblink.rocketreserver.fragment.PostF
import com.starblink.rocketreserver.type.HashtagPostParam
import kotlinx.coroutines.launch

class TopicDetailVM : BaseViewModel() {
    var page: Int = 1
    lateinit var topicId: String
    var mList: MutableLiveData<ArrayList<PostF>> = MutableLiveData(arrayListOf())
    var data: MutableLiveData<HashtagPostVOF> = MutableLiveData()

    fun getRecommend() {
        viewModelScope.launch {
            val response = SkGqlClient.skQuery(
                SearchHashtagPostQuery(
                    hashtagPostParam = HashtagPostParam(
                        hashtagId = Optional.present(topicId),
                        postId = Optional.present(""),
                        pageNo = Optional.present(page),
                        pageSize = Optional.present(20)
                    )
                )
            )

            if (response?.data != null) {
                if (response.data!!.searchHashtagPost != null && response.data!!.searchHashtagPost!!.hashtagPostVOF != null) {
                    val hashtagPostVOF = response.data!!.searchHashtagPost!!.hashtagPostVOF
                    data.value = hashtagPostVOF
                    var list1 = hashtagPostVOF.posts
                    var list = arrayListOf<PostF>()
                    list1!!.forEach { e ->
                        if (e != null) {
                            list.add(e.postF)
                            var imgUrl = e.postF.mainPic
                            ImageUtils.preloadImage(commContext(), imgUrl)
                        }
                    }
                    page++
                    mList.value?.addAll(list)
                    mList.value = mList.value
                }
            }
        }
    }

}